package br.com.efacta.bagarita.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import br.com.efacta.bagarita.domain.auth.User;
import br.com.efacta.bagarita.domain.repos.UserRepository;

@Service("bagaritaUserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepo;

    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        if (StringUtils.isNotBlank(login)) {
            List<User> result = userRepo.findByLogin(login);
            if (result != null && result.size() == 1) {
                User user = result.get(0);
                return new UserWrapper(user);
            }
        }
        return null;
    }


    private class UserWrapper implements UserDetails {

        /**
         * 
         */
        private static final long serialVersionUID = 4867342255470932567L;

        private User user;

        public UserWrapper(User user) {
            this.user = user;
        }

        public Collection<? extends GrantedAuthority> getAuthorities() {
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            for (String role : user.getRoles()) {
                authorities.add(new SimpleGrantedAuthority(role));
            }
            return authorities;
        }

        public String getPassword() {
            return user.getPassword();
        }

        public String getUsername() {
            return user.getLogin();
        }

        public boolean isAccountNonExpired() {
            return true;
        }

        public boolean isAccountNonLocked() {
            return true;
        }

        public boolean isCredentialsNonExpired() {
            return true;
        }

        public boolean isEnabled() {
            return user.isEnabled();
        }

    }
}
